# problem id: 6207
# url: https://leetcode-cn.com/contest/weekly-contest-285/problems/count-hills-and-valleys-in-an-array/


class Solution:
    def countHillValley(self, nums: List[int]) -> int:
        count = 0
        length = len(nums)
        idx = 1
        while True:
            if idx >= length - 1:
                break
            item = nums[idx]
            left_index, right_index = idx - 1, idx + 1

            left_index = self.find_left_index(item, nums, left_index)
            right_index = self.find_right_index(item, nums, right_index, length)
            idx = min(right_index, length - 1)

            if (item > nums[left_index] and item > nums[right_index]) or \
                    (item < nums[left_index] and item < nums[right_index]):
                count += 1

        return count

    @staticmethod
    def find_left_index(item, nums, left_index):
        while True:
            if item == nums[left_index]:
                left_index -= 1
                if left_index <= 0:
                    left_index = 0
                    break
            else:
                break
        return left_index

    @staticmethod
    def find_right_index(item, nums, right_index, length):
        while True:

            if item == nums[right_index]:
                right_index += 1
                if right_index >= length - 1:
                    right_index = length - 1
                    break
            else:
                break
        return right_index
